<!--
 * @Descripttion: 
 * @Author: jhw
 * @Date: 2024-06-14 15:33:02
 * @LastEditors: jhw
 * @LastEditTime: 2024-06-17 15:51:19
-->
<template>
  <div>
    <el-table :data="data" style="width: 100%" v-bind="$attrs">
      <slot>
        <el-table-column v-for="(item, index) in columns" v-bind="item" :key="index">
          <template v-if="item.type !== 'selection' && item.type !== 'index'" #default="{ row, $index }">
            <span v-if="item.prop === 'index'">{{
              (queryParams.pageNumber - 1) * queryParams.pageSize + $index + 1
            }}</span>
            <slot
              v-else-if="item.type === 'slot' && item.slotName"
              :name="item.slotName"
              :item="item"
              :row="row"
              :index="$index"
            ></slot>
            <span v-else>{{ row[item.prop] || '-' }}</span>
          </template>
        </el-table-column>
      </slot>
      <template #empty>
        <div class="flex-column g-empty-table-box">
          <span class="g-empty-table-box--txt">暂无数据</span>
        </div>
      </template>
    </el-table>
    <el-pagination
      v-model:current-page="queryParams.pageNumber"
      v-model:page-size="queryParams.pageSize"
      layout="prev, pager, next, jumper"
      :total="total"
      :hide-on-single-page="true"
      @size-change="onPageSizeChange"
      @current-change="onPageChange"
    />
  </div>
</template>

<script setup lang="ts">
import { PropType, toRefs } from 'vue';
import { TableConfig } from './config';

const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  config: {
    type: Object as PropType<TableConfig>,
    default: () => ({}),
  },
});

const emit = defineEmits(['update:queryParams', 'pageChange']);

const { columns, queryParams, total } = toRefs(props.config);
const onPageChange = (page: number) => {
  emit('update:queryParams', {
    ...queryParams.value,
    pageNumber: page,
  });
  emit('pageChange');
};
const onPageSizeChange = (pageSize: number) => {
  let { pageNumber } = queryParams.value;
  if (pageNumber * pageSize > total.value) {
    pageNumber = 1;
  }
  emit('update:queryParams', { pageNumber, pageSize });
  emit('pageChange');
};
</script>

<style scoped>
.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}
</style>
